package com.luinnx.message.servlet;

import com.luinnx.message.DB.DB;
import com.luinnx.message.model.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sun.management.resources.agent;

@SuppressWarnings({ "serial", "unused" })
public class registerServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		// 设置编码
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("UTF-8");

		// 获取参数
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String password2 = req.getParameter("password2");
		String age = req.getParameter("age");
		String  cellphone = req.getParameter("cellphone");
		String email = req.getParameter("email");

//		输出检验
		System.out.println(username);
		System.out.println(password);
		System.out.println(age);
		System.out.println(cellphone);
		System.out.println(email);
		
		// 注册用户和保存用户信息
		HttpSession session=req.getSession();
		User user=new User();
		DB db=new DB();
		if(username !=null && password != null){
			if(password.length()>=6){
				if(password.equals(password2)){
					user.setUsername(username);
					user.setPassword(password);
					user.setAge(age);
					user.setCellphone(cellphone);
					user.setEmail(email);
					
					if(db.insertUser(user)){
						user.setId(db.getUserId(username));//获取用户插入数据库的id值
						session.setAttribute("user", user);
						
						resp.sendRedirect("main.jsp");
					}else{
						resp.sendRedirect("error.jsp");
					}
				
				}else {
					System.out.println("两次密码输入不相等！请重新输入！");
					resp.sendRedirect("pwerror.jsp");
				}
			}else {
				System.out.println("密码长度小于6位，请重新输入！");
				resp.sendRedirect("pwerror.jsp");
			}
			
		}
	}

}